import { useState, useEffect, useRef } from 'react'
import Taro from '@tarojs/taro'
import { Picker } from '@tarojs/components'
import { AtList, AtListItem } from 'taro-ui'

import * as api from 'src/api'

import './index.scss'

type Props = {
  value: any
  onChange: (any) => void
}

export default ({ value, onChange }: Props) => {
  const [range, setRange] = useState([[], [], []])
  const [key, setKey] = useState([0, 0, 0])
  const citys = useRef<any[]>([])
  useEffect(() => {
    citys.current = Taro.getStorageSync('city_list')
    if (!citys.current || citys.current.length <= 0) {
      api.getCity().then((res) => {
        Taro.setStorage({ key: 'city_list', data: res })
        citys.current = res
        initKey()
      })
    } else {
      initKey()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const initKey = () => {
    try {
      const indexKey: number[] = [0, 0, 0]
      if (value.province) {
        indexKey[0] = citys.current.findIndex(
          ({ name }) => name === value.province
        )
        indexKey[1] = citys.current[indexKey[0]].child.findIndex(
          ({ name }) => name === value.city
        )
        indexKey[2] = citys.current[indexKey[0]].child[
          indexKey[1]
        ].child.findIndex(({ name }) => name === value.district)
      }
      setKey(indexKey)
      initRange(indexKey)
    } catch (error) {
      Taro.showToast({ title: '城市列表获取失败', icon: 'none' })
    }
  }

  const initRange = (pickerKey) => {
    const cityChildren = citys.current[pickerKey[0]]?.child || []
    const areaChildren = cityChildren.length
      ? cityChildren[pickerKey[1]]?.child || []
      : []
    setRange([
      citys.current.map(({ name }) => name),
      cityChildren.map(({ name }) => name),
      areaChildren.map(({ name }) => name),
    ])
    setKey(pickerKey)
  }

  const handleChangePicker = (e) => {
    const valueKey = e.detail.value
    const address = {
      province: '',
      city: '',
      district: '',
      cityId: 0,
    }
    if (citys.current[valueKey[0]]) {
      address.province = citys.current[valueKey[0]].name
      if (citys.current[valueKey[0]]?.child[valueKey[1]]) {
        address.city = citys.current[valueKey[0]].child[valueKey[1]].name
        address.cityId = citys.current[valueKey[0]].child[valueKey[1]].cityId
        if (
          citys.current[valueKey[0]]?.child[valueKey[1]]?.child[valueKey[2]]
        ) {
          address.district =
            citys.current[valueKey[0]].child[valueKey[1]].child[
              valueKey[2]
            ].name
        }
      }
    }
    setKey(valueKey)
    onChange(address)
  }

  const handleColumnChange = (e) => {
    const { column, value: valueIndex } = e.detail
    switch (column) {
      case 0:
        initRange([valueIndex, 0, 0])
        break
      case 1:
        initRange([key[0], valueIndex, 0])
        break
      case 2:
        initRange([key[0], key[1], valueIndex])
        break
    }
  }

  return (
    <Picker
      className="address-picker"
      mode="multiSelector"
      range={range}
      value={key}
      onColumnChange={handleColumnChange}
      onChange={handleChangePicker}
    >
      <AtList>
        <AtListItem
          title="所在地区"
          extraText={
            value.province
              ? `${value.province}${value.city}${value.district}`
              : '请选择省/市/区'
          }
        />
      </AtList>
    </Picker>
  )
}
